<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="listCertificate"
    :columns="columns"
    row-key="refugeId"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="refuge:add">新增</b-button>
        <b-button
          icon="delete"
          @click="onDelete()"
          :disabled="!selectedRowKeys.length"
          code="refuge:remove"
          >删除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button
        icon="edit"
        type="link"
        @click="onView(record)"
        code="refuge:query"
        >详情</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items">
    <template #map="{ formState }">
      <div class="h-96">
        <lbs-map
          v-model:lat="formState['latitude']"
          v-model:lng="formState['longitude']"
          @click="
            (marker) => {
              mapClick(marker, formState);
            }
          "
        />
      </div>
    </template>
  </FormModal>
</template>

<script setup lang="tsx">
import { computed, ref } from 'vue';
import { hasPermission } from '@/permission';
import { Modal, Space, message } from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { LbsMap } from '@/components/map';
import { useFormModal } from '@/hooks/formModal';
import { listToEnum, listToOption } from '@/utils/utils';
import {
  addShelter,
  delShelter,
  getAddress,
  listCertificate,
  updateShelter,
} from '@/api/base';
import { fetchDictsOfType } from '@/api/dict';

const selectedRowKeys = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectedRowKeys.value,
    onChange(values, all) {
      selectedRowKeys.value = values as number[];
    },
  };
});
const tableRef = ref();
const sysLevelOption = ref<Global.Option[]>([]);
const sysLevelEnum = ref<Record<string, any>>({});
const sysCategoryOption = ref<Global.Option[]>([]);
const sysCategoryEnum = ref<Record<string, any>>({});
const init = () => {
  fetchDictsOfType(['sys_level', 'sys_category']).then((res: any) => {
    const { sys_level, sys_category } = res.data;
    sysLevelEnum.value = listToEnum(sys_level, 'dictValue', 'dictLabel');
    sysLevelOption.value = listToOption(sys_level, 'dictLabel', 'dictValue');
    sysCategoryEnum.value = listToEnum(sys_category, 'dictValue', 'dictLabel');
    sysCategoryOption.value = listToOption(
      sys_category,
      'dictLabel',
      'dictValue',
    );
  });
};
init();

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '序号',
    dataIndex: 'index',
    fixed: 'left',
    width: 60,
    hideInSearch: true,
    customRender({ pageSize, pageNum, index }) {
      return (pageNum.value - 1) * pageSize.value + index + 1;
    },
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '类别',
    dataIndex: 'category',
    valueEnum: { ...sysCategoryEnum.value },
  },
  {
    title: '面积（平方米）',
    dataIndex: 'acreage',
    hideInSearch: true,
  },
  {
    title: '容纳人数',
    dataIndex: 'capacity',
    hideInSearch: true,
  },
  {
    title: '级别',
    dataIndex: 'level',
    valueEnum: { ...sysLevelEnum.value },
  },
  {
    title: '有效面积（平方米）',
    dataIndex: 'validArea',
    hideInSearch: true,
  },
  {
    title: '所在地址',
    dataIndex: 'address',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 80,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '名称',
    type: 'input',
    field: 'name',
    rules: [
      {
        required: true,
        message: '请输入名称',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入名称',
    },
  },
  {
    label: '类别',
    type: 'select',
    field: 'category',
    rules: [
      {
        required: true,
        message: '请选择类别',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择类别',
      options: sysCategoryOption.value,
    },
  },
  {
    label: '面积',
    type: 'input',
    field: 'acreage',
    props: {
      placeholder: '请输入面积',
      addonAfter: '平方米',
    },
  },
  {
    label: '级别',
    type: 'select',
    field: 'level',
    rules: [
      {
        required: true,
        message: '请选择级别',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请选择级别',
      options: sysLevelOption.value,
    },
  },
  {
    label: '有效面积',
    type: 'input',
    field: 'validArea',
    props: {
      placeholder: '请输入有效面积',
      addonAfter: '平方米',
    },
  },
  {
    label: '容纳人数',
    type: 'input',
    field: 'capacity',
    props: {
      placeholder: '请输入容纳人数',
    },
  },
  {
    label: '所在地址',
    type: 'input',
    field: 'address',
    rules: [
      {
        required: true,
        message: '请输入详细地址',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入详细地址',
    },
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
    colProps: {
      span: 24,
    },
  },
  {
    label: '经度',
    type: 'input',
    field: 'longitude',
    rules: [
      {
        required: true,
        message: '请输入经度',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入经度',
    },
  },
  {
    label: '纬度',
    type: 'input',
    field: 'latitude',
    rules: [
      {
        required: true,
        message: '请输入纬度',
        trigger: 'blur',
      },
    ],
    props: {
      placeholder: '请输入纬度',
    },
  },
  {
    label: '地图',
    type: 'input',
    field: 'map',
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
    colProps: {
      span: 24,
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 2,
  formProps: { labelCol: { span: 6 } },
});
const mapClick = async ([lat, lon]: any, formState: any) => {
  const res = await getAddress(lon, lat);
  formState.address = res.msg;
};
const onAdd = () => {
  open({
    title: '新增',
    defaultValue: {
      addressList: [],
    },
    serviceApi: async (params: any): Promise<any> => {
      await addShelter(params);
      tableRef.value.refresh();
    },
  });
};
const onView = (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: { ...record },
    hasEditPermission: hasPermission('refuge:edit'),
    serviceApi: async (params: any): Promise<any> => {
      await updateShelter(params);
      tableRef.value.refresh();
    },
    hasEditPermission: hasPermission('refuge:edit'),
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};
const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `是否确认删除当前项？`,
    onOk: async () => {
      await delShelter(selectedRowKeys.value.join());
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};
</script>
